<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="800px"
    title="新建保证金"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :inline="true"
      :rules="formRules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="保证金类型"
            prop="marginType"
            style="width: 100%"
          >
            <el-select
              v-model="formData.marginType"
              style="width: 100%"
              placeholder="请选择保证金类型"
              @change="refreshList"
            >
              <el-option
                v-for="(item,index) in cashDepositTypeOption"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="保证金"
            prop="marginMoney"
            style="width: 100%"
          >
            <el-input
              v-model="formData.marginMoney"
              style="width: 100%"
              placeholder="请输入保证金"
              @input="formData.marginMoney=formData.marginMoney.replace(/^\.+|[^\d.]/g,'')"
            >
              <template #append>
                <span>元</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款方类型"
            prop="payerType"
            style="width: 100%"
          >
            <el-select
              v-model="formData.payerType"
              style="width: 100%"
              placeholder="请选择付款方类型"
              @change="payerTypeChange"
            >
              <el-option
                v-for="(item,index) in payerTypeOption.filter(p => p.value !=='direct')"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款方名称"
            prop="marginType"
            style="width: 100%"
          >
            <el-select
              v-model="formData.payerId"
              style="width:100%"
              filterable
              remote
              reserve-keyword
              :disabled="formData.payerType?false:true"
              placeholder="请输入关键词"
              :remote-method="customerQuerySearch"
              :loading="customerLoading"
              @change="handleCustomerSelect"
            >
              <el-option
                v-for="(item) in customerOption"
                :key="item.id"
                :label="formData.payerType ==='agent'||formData.payerType ==='agent_person'?item.agentName:formData.payerType ==='terminal'?item.terminalName:''"
                :value="item.id"
              >
                <div class="productName">
                  <span v-if="formData.payerType ==='agent'||formData.payerType ==='agent_person'">{{ item.agentName }}</span>
                  <span v-if="formData.payerType ==='terminal'">{{ item.terminalName }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款开户行"
            prop="paymentBank"
            style="width: 100%"
          >
            <el-input
              v-model="formData.paymentBank"
              style="width: 100%"
              placeholder="请输入付款开户行"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款账号"
            prop="paymentAccount"
            style="width: 100%"
          >
            <el-input
              v-model="formData.paymentAccount"
              style="width: 100%"
              placeholder="请输入付款账号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="付款日期"
            prop="payerTime"
            style="width: 100%"
          >
            <date-picker
              v-model:date="formData.payerTime"
              style="width: 100%"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'
import {crmStore} from '@CRM/store'

export default defineComponent({
  name: 'CreateCashDeposit',
  emits: ['handleSuccess'],
  setup(props, context) {
    const api = inject('api')
    const formRef = ref(null)
    const currentInstance = getCurrentInstance()
    var datas = reactive({
      cashDepositTypeOption:
        crmStore.getters['dictionary/getDictionary']['payee_type'],
      payerTypeOption:
        crmStore.getters['dictionary/getDictionary']['agent_type'],
      formData: {
        marginType: '',
        marginMoney: undefined,
        payerType: '',
        payerId: undefined,
        payerName: '',
        paymentBank: '',
        paymentAccount: '',
        payerTime: undefined,
      },
      customerLoading: false,
      customerOption: [],
    })
    const marginMoneyPass = (rule, value, callback) => {
      if (Number(value) >= 0) {
        if (value > 0) {
          datas.formData.marginMoney = Number(value)
          callback()
        } else {
          callback(new Error('保证金必须大于0'))
        }
      } else {
        callback(new Error('请输入保证金'))
      }
    }
    var formRules = reactive({
      marginType: [
        { required: true, message: '请选择保证金类型', trigger: 'change' },
      ],
      marginMoney: [
        { required: true, validator: marginMoneyPass, trigger: 'blur' },
      ],
      payerType: [
        { required: true, message: '请选择付款方类型', trigger: 'change' },
      ],
      payerId: [{ required: true, message: '请选择付款方', trigger: 'change' }],
      paymentBank: [
        { required: true, message: '请输入开户行', trigger: 'blur' },
      ],
      paymentAccount: [
        { required: true, message: '请输入付款账号', trigger: 'blur' },
      ],
      payerTime: [
        { required: true, message: '请选择付款时间', trigger: 'change' },
      ],
    })
    var formLabelWidth = ref(100)
    var dialogShow = ref(false)
    const open = () => {
      dialogShow.value = true
    }
    const close = () => {
      dialogShow.value = false
      formRef.value.resetFields()
    }
    const payerTypeChange = (val) => {
      datas.customerOption = []
    }
    const customerQuerySearch = async(queryString, cb) => {
      datas.customerLoading = true
      const a = {
        module_type: datas.formData.payerType,
        key_word: queryString,
      }
      let results = []
      const res = await api.terminal.CONTRACT_NAME(a)
      if (res.code === 0) {
        datas.customerLoading = false
        results = res.data.list || []
        datas.customerOption = results
      }
    }

    const handleCustomerSelect = (val) => {
      var sel = datas.customerOption.find((p) => p.id === val)
      switch (datas.formData.payerType) {
        case 'agent':
          datas.formData.payerName = sel.agentName
          break
        case 'terminal':
          datas.formData.payerName = sel.terminalName
          break
      }
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          api.cashDeposit.CASH_DEPOSIT_CREATE(datas.formData).then((res) => {
            if (res.code === 0) {
              context.emit('handleSuccess')
              close()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      formRef,
      ...toRefs(datas),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      customerQuerySearch,
      handleCustomerSelect,
      payerTypeChange,
    }
  },
})
</script>
